package com.sc.generatorcode.task;

import com.sc.generatorcode.entity.ColumnInfo;
import com.sc.generatorcode.task.base.AbstractTask;
import com.sc.generatorcode.utils.*;
import com.sc.generatorcode.utils.*;
import freemarker.template.TemplateException;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author ：wust
 * @date：2019-12-26
 */
public class MapperXmlTask extends AbstractTask {

    /**
     * 单表Mapper
     */
    public MapperXmlTask(String className, String tableName, List<ColumnInfo> infos) {
        this(tableName, className, null, null, null, infos, null);
    }

    /**
     * 一对多Mapper
     */
    public MapperXmlTask(String tableName, String className, String parentTableName, String parentClassName, String foreignKey, List<ColumnInfo> tableInfos, List<ColumnInfo> parentTableInfos) {
        this(tableName, className, parentTableName, parentClassName, foreignKey, null, null, tableInfos, parentTableInfos);
    }

    /**
     * 多对多Mapper
     */
    public MapperXmlTask(String tableName, String className, String parentTableName, String parentClassName, String foreignKey, String parentForeignKey, String relationalTableName, List<ColumnInfo> tableInfos, List<ColumnInfo> parentTableInfos) {
        super(tableName, className, parentTableName, parentClassName, foreignKey, parentForeignKey, relationalTableName, tableInfos, parentTableInfos);
    }

    @Override
    public void run() throws IOException, TemplateException {
        Map<String, String> mapperData = new HashMap<>();
        mapperData.put("DaoPackageName", ConfigUtil.getConfiguration().getBasePackage().getDao());
        mapperData.put("ClassName", className);
        mapperData.put("EntityName", className);
        mapperData.put("ResultMap", GeneratorUtil.generateMapperResultMap(columnInfos));
        mapperData.put("Association", "");
        mapperData.put("Collection", "");

        String filePath = FileUtil.getResourcePath() + StringUtil.package2Path(ConfigUtil.getConfiguration().getPath().getMapper());
        String fileName = className + "Mapper.xml";
        FileUtil.generateFile(FreemarkerConfigUtils.TYPE_MAPPER, mapperData, filePath,fileName);
    }

    private ColumnInfo getPrimaryKeyColumnInfo(List<ColumnInfo> list) {
        for (ColumnInfo columnInfo : list) {
            if (columnInfo.isPrimaryKey()) {
                return columnInfo;
            }
        }
        return null;
    }

}
